package com.zxt.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.zxt.domain.Address;
import com.zxt.domain.User;
import com.zxt.service.AddressService;
import com.zxt.service.UserService;
import com.zxt.service.impl.AddressServiceImpl;
import com.zxt.service.impl.UserServiceImpl;
import com.zxt.util.Base64Utils;
import com.zxt.util.RandomUtil;
import com.zxt.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * projectName:myXiaoMi
 * author:ZhangXiaoTeng
 * time:2021/12/3 17:52
 * description:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //进行校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/register.jsp";
        }
        if (!password.equals(repassword)) {
            request.setAttribute("msg", "两次密码输入有误");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(email)) {
            request.setAttribute("msg", "邮箱不能为空");
            return "/register.jsp";
        }
        //验证用户名是否已经存在
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUsername(username);
        if (b) {
            request.setAttribute("msg", "用户名已存在");
            return "/register.jsp";
        }

        //创建用户
        User user = new User(0, username, password, email, gender, 0, 1, RandomUtil.createActiveCode());
        try {
            userService.regist(user);
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            request.setAttribute("msg", "注册失败" + e.getMessage());
            return "/register.jsp";
        }
    }

    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        //1.创建验证
        ValidateCode validateCode = new ValidateCode(100, 28, 4, 20);
        //2.把验证码存入session
        request.getSession().setAttribute("vcode", validateCode.getCode());
        System.out.println(validateCode.getCode());
        //3.返回客户端
        validateCode.write(response.getOutputStream());
        return null;

    }


    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        //新增自动登录
        String auto = request.getParameter("auto");


        //2.校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/login.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/login.jsp";
        }
        if (StringUtils.isEmpty(vcode)) {
            request.setAttribute("msg", "验证码不能为空");
            return "/login.jsp";
        }
        //进行验证  验证码是否正确
        String code = (String) request.getSession().getAttribute("vcode");
        if (!vcode.equalsIgnoreCase(code)) {
            request.setAttribute("msg", "验证码错误");
            return "/login.jsp";
        }
        //2.调用业务逻辑
        try {
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            //存储用户转发或重定向
            request.getSession().setAttribute("user", user);


            //新增自动登录
            System.out.println(auto);
            if (auto != null) {
                //自动登录
                //创建Cookie
                String userinfo = username + "#" + password;
                //Base64处理
                userinfo = Base64Utils.encode(userinfo);
                Cookie cookie = new Cookie("userinfo", userinfo);
                //设置回写路径
                cookie.setPath(request.getContextPath());
                //有效期
                cookie.setMaxAge(14 * 24 * 60 * 60);   //自动登录期限 14天
                //设置Httponly
                cookie.setHttpOnly(true);
                //回写
                response.addCookie(cookie);
            }
            return "redirect:/index.jsp";
        } catch (Exception e) {
            request.setAttribute("msg", "登录失败" + e.getMessage());
            return "/login.jsp";
        }

    }


    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username:" + username);
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");
            return null;
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUsername(username);
        if (b) {  //true    用户已存在 1
            response.getWriter().write("1");
            return null;
        }
        response.getWriter().write("0"); //可以使用
        //转发重定向
        return null;
    }

    public String loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.将session 中的用户删除
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //2.session失效
        session.invalidate();
        //3.删除自动登录的cookie
        Cookie Cookie = new Cookie("userinfo", "");
        Cookie.setPath(request.getContextPath());
        Cookie.setMaxAge(0);
        response.addCookie(Cookie);
        return "redirect:/index.jsp";
    }


    //---------------------------------------------Address地址模块-----------------------------------------------

    //添加地址
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //进行校验
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收货人姓名不能为空");
            return "/address_info.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "电话不能为空");
            return "/address_info.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收货地址不能为空");
            return "/address_info.jsp";
        }
        //调用业务逻辑
        AddressService addressService = new AddressServiceImpl();
        Address address = new Address(0, detail, name, phone, user.getId(), 0);
        try {
            addressService.add(address);
            //转发重定向
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            request.setAttribute("msg", "添加地址失败" + e.getMessage());
            return "/address_info.jsp";
        }
    }


    //查看所有地址
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }

        //调用业务逻辑
        AddressService addressService = new AddressServiceImpl();
        try {
            List<Address> addList = addressService.find(user.getId());
            //转发重定向
            request.setAttribute("addList", addList);
        } catch (Exception e) {
            request.setAttribute("msg", "查询地址失败" + e.getMessage());
        }
        return "/address_info.jsp";

    }


    //删除地址
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //获取前端数据
        String id = request.getParameter("id");
        ///校验
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "用户id不能为空");
            return "/address_info.jsp";
        }
        //调用业务逻辑
        AddressService addressService = new AddressServiceImpl();
        try {
            addressService.remove(user.getId(), Integer.parseInt(id));
            //转发重定向
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            request.setAttribute("msg", "删除地址失败" + e.getMessage());
            return "/address_info.jsp";

        }
    }


    //设为默认地址 (其实是数据一个更新操作 在数据库)
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //获取前端数据
        String id = request.getParameter("id");
        ///校验
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "用户id不能为空");
            return "/address_info.jsp";
        }
        //调用业务逻辑
        AddressService addressService = new AddressServiceImpl();
        try {
            addressService.updateLevel(user.getId(), Integer.parseInt(id));
            //转发重定向
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            request.setAttribute("msg", "设置默认地址失败" + e.getMessage());
            return "/address_info.jsp";

        }
    }


    //修改地址
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "用户id不能为空");
            return "/address_info.jsp";
        }
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "用户id不能为空");
            return "/address_info.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "用户姓名不能为空");
            return "/address_info.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "用户详细地址为空");
            return "/address_info.jsp";
        }

        //3.调用业务逻辑
        AddressService addressService = new AddressServiceImpl();
        try {
            Address address = new Address(Integer.parseInt(id), detail, name, phone, user.getId(), Integer.parseInt(level));
            addressService.update(address);
            //转发重定向
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            request.setAttribute("msg", "修改地址失败" + e.getMessage());
            return "/address_info.jsp";

        }
    }

    //------------------------------------------------------------------------后台操作------------------------------------------------
    public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //进行校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/message.jsp";
        }

        //用户名和密码进行验证

        //调用业务逻辑
        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username,password);
            if (user != null) {
                //存储数据
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                //转发重定向
                return "redirect:/admin/admin.jsp";
            }else{
                //转发重定向
                request.setAttribute("msg", "用户名或密码错误");
                return "/message.jsp";
            }

        } catch (Exception e) {
            request.setAttribute("msg", "用户名或密码错误");
            return "/message.jsp";
        }
    }


}